package com.culturalCenter.dataCenter.controller;

import com.culturalCenter.dataCenter.Utils.ApiResult;
import com.culturalCenter.dataCenter.Utils.JwtTokenUtils;
import com.culturalCenter.dataCenter.Utils.RedisUtil;
import com.culturalCenter.dataCenter.Utils.ResultCode;
import com.culturalCenter.dataCenter.customEntity.requestParam.RequestToken;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.culturalCenter.dataCenter.Utils.ApiResult.instance;

/**
 * token刷新类
 */
@Api(tags = "token接口类 20200711")
@ApiSupport(author = "wulincheng")
@RestController
@RequestMapping("api")
@Slf4j
public class TokenController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private RestTemplate restTemplate;
    @Value("${jwt.head}")
    private String head;
    @Value("${server.port}")
    private String port;

    @PostMapping("token")
    public ApiResult token(HttpServletRequest requests, @RequestBody @Valid RequestToken requestToken) {
        // 返回服务器的主机名
        String ServerName = requests.getServerName();
        // 返回服务器的端口号
        int ServerPort = requests.getServerPort();
        // 获取的是使用的协议(http 或https)
        String http = requests.getScheme();

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // new HttpEntity<>(map, headers);
        HttpEntity<RequestToken> request = new HttpEntity<>(requestToken, headers);

        String url = http + "://" + ServerName + (ServerPort > 0 ? ":" + ServerPort : "") + "/api/login";
        ResponseEntity<String> results = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        // String data = results.getBody();
        return instance(ResultCode.SUCCESS, results.getBody());
    }

    @GetMapping("refreshToken")
    public ApiResult<Map<String, Object>> refreshToken(String token) {
        Claims claims = JwtTokenUtils.getClaimsFromToken(token);
        if (claims == null) {
            log.warn("token不存在");
            return instance(ResultCode.UNAUTHORIZED, null);
        }
        String refToken = JwtTokenUtils.refreshToken(token);
        // 过期时间
        Date time = JwtTokenUtils.getClaimsFromToken(refToken).getExpiration();
        // 保存token
        RedisUtil ru = new RedisUtil(redisTemplate);
        Map<String, Object> result = new HashMap<>();

        result.put("token", head + refToken);
        result.put("expire", time.getTime());
        ru.setExpire((String) claims.get("username"), refToken, time.getTime());
        return instance(ResultCode.SUCCESS, result);
    }

    @GetMapping("checkToken")
    public ApiResult checkToken(String token) {
        Claims claims = JwtTokenUtils.getClaimsFromToken(token);
        Date expiredTime = claims.getExpiration();
        return (System.currentTimeMillis() > expiredTime.getTime()) ? instance(ResultCode.UNAUTHORIZED, null) : instance(ResultCode.SUCCESS, null);
    }

}
